<?php
/**
 * Created by PhpStorm.
 * User: dream
 * Date: 2017/10/15
 * Time: 11:03
 */
require_once __DIR__.'/phpmailer/autoload.php';

class SendMail
{
    private $config_path = __DIR__.'/mail.json';
    private $mailer;
    private $mail_conf;

    //初始化参数
    public function __construct($default_mailer=true)
    {
        if($default_mailer)
        {
            $this->loadConfig();
            $this->init();
        }
    }

    //初始化
    public function init()
    {
        $mail_config = $this->mail_conf;
        $mailer = new \PHPMailer\PHPMailer\PHPMailer();
        $this->mailer = $mailer;
        $this->mailer->Mailer = $mail_config["mail_type"];
        $this->mailer->SMTPDebug = empty($mail_config['debug'])?0:1;
        $this->mailer->SMTPAuth = true;
        $this->mailer->Host = $mail_config['host'];
        $this->mailer->SMTPSecure = isset($mail_config['secure_type']) ? $mail_config['secure_type'] : 'ssl';
        $this->mailer->Port = $mail_config['port'];
        $this->mailer->CharSet= $mail_config['charset'];
        $this->mailer->Hostname = $mail_config['my_domain'];
        $this->mailer->FromName = $mail_config['from_name'];
        $this->mailer->Username = $mail_config['user_name'];
        $this->mailer->Password = $mail_config['pass_word'];
        $this->mailer->From = $mail_config['from'];
        if($mail_config['is_html'])
        {
            $this->mailer->isHTML(true);
        }
        else{
            $this->mailer->isHTML(false);
        }
        if(isset($mail_config['config_path']))
            $this->config_path = $mail_config['config_path'];
    }

    //设置config
    public function setConfig($name,$value)
    {
        $this->mail_conf[$name] = $value;
    }

    //获取配置信息
    public function getConfig()
    {
        return $this->mail_conf;
    }

    //加载配置
    public function loadConfig()
    {
        $mail_config_json = @file_get_contents($this->config_path);
        $mail_config = json_decode($mail_config_json, true);
        $this->mail_conf = $mail_config;
    }

    //获取错误信息
    public function getErrorInfo()
    {
        return $this->mailer->ErrorInfo;
    }

    //发送邮件
    public function sendMail($to,$subject,$body,$nick_name="")
    {
       $this->mailer->addAddress($to,$nick_name);
       $this->mailer->Subject = $subject;
       $this->mailer->Body = $body;
       $status = $this->mailer->send();
       if($this->mail_conf['debug'])
       {
           return $this->getErrorInfo();
       }else{
           return $status;
       }
    }

}